package com.fingard.dsp.bank.directbank.spdb11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAuthorizeForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.*;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.ReqAuthForRecDetail;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryAuthForRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 浦发批量代扣签约
 *
 * @author fanghh
 * @version 1.0
 */
public class SPDB11AuthorizeForRec extends SPDB11Base implements IAuthorizeForRec {
    /**
     * 批量代扣授权：UBCS
     */
    @SuppressWarnings("deprecation")
	@Override
    public RetAtsAuthForRec d_auth(ReqAuthForRec p_req) {
        RetAtsAuthForRec retAts = new RetAtsAuthForRec(p_req.reqHeader);
        try {
            StringBuilder sbFileContent = new StringBuilder();
            // 文件头
            String tmpReqHeader = MessageFormat.format("F※{0}※1002※{1}※※※N\n", bankFront.corpNo, p_req.totalNum);
            sbFileContent.append(tmpReqHeader);
            // 文件明细
            while (p_req.readRecord()) {
                ReqAuthForRecDetail tmpDetail = p_req.readedDetail;
                String cardType = p_req.readedDetail.cardType;
                if (StringHelper.isNullOrEmpty(cardType)) {
                    cardType = "2";
                } else if ("1".equals(cardType)) {
                    cardType = "2";// 存折
                } else {
                    cardType = "1";// 卡
                }
                String certType = convertCertTypeToBank(tmpDetail.certType);
                
                String useCode = tmpDetail.oppAct;
                if (getBankConfig().getValueAsBool("fixUseCode")) {
                	useCode = p_req.readedDetail.insuPolicyNum;
                }
                // 签约序号※客户账户类型※客户账号※姓名※证件种类※证件号码※第三方号码※操作标志※是否浦发代销客户※备注1※备注2※密文\n
                String tmpReqBodyDetail = MessageFormat.format("※{0}※{1}※{2}※{3}※{4}※{5}※1※1※{6}※※\n", cardType, tmpDetail.oppAct, tmpDetail.oppActName, certType, tmpDetail.certNum, useCode, tmpDetail.authCode);
                sbFileContent.append(tmpReqBodyDetail);
            }

            String tmpReqData = sbFileContent.toString();
            WriteBankLogStep2(tmpReqData);
            // 上传文件名保存本地，查询时用
            Date tmpPayDateTime = new Date();
            //日切时间配置
            String dayChangeConfig = getBankConfig().getValueAsString("dayChangeTime");
            Date  dayChangeTime=  Format.Time8Format.parse(dayChangeConfig);

            if ((tmpPayDateTime.getHours()*60*60+tmpPayDateTime.getMinutes()*60+tmpPayDateTime.getSeconds())>=
                    (dayChangeTime.getHours()*60*60+dayChangeTime.getMinutes()*60+dayChangeTime.getSeconds())) {
                Calendar tmpPayCalendar = Calendar.getInstance();
                tmpPayCalendar.setTime(tmpPayDateTime);
                tmpPayCalendar.add(Calendar.DAY_OF_YEAR, 1);
                tmpPayDateTime = tmpPayCalendar.getTime();
            }
            String tmpMarkDataDir = getDataFileDirectory(tmpPayDateTime) + File.separator + "auth";
            int maxBatch = 0;
            File dataFileDir = new File(tmpMarkDataDir);
            if (dataFileDir.exists()) {
                int len = dataFileDir.listFiles().length;
                if (len > 0) {
                    maxBatch = len + 1;
                } else {
                    maxBatch = 1;
                }
            } else {
                maxBatch = 1;
            }
            // 文件名命名规则: UBCS_保险公司编号(4位) _机构代码（4位）_日期（8位）_序号（2位）
            String tmpUpFilePrefix = "UBCS_" + bankFront.corpNo + "_" + bankFront.org + "_" + Format.Date8Format.format(tmpPayDateTime) + "_" + String.format("%2s", maxBatch).replace(" ", "0");
            String tmpUpFileName = tmpUpFilePrefix + ".TXT";
            String tmpLocalMarkPath = StringHelper.trimEnd(tmpMarkDataDir, File.separator) + File.separator + p_req.reqSeqID + ".TXT";
            WriteBankLogLn2("批次号映射文件路径: " + tmpLocalMarkPath);
            FileHelper.writeFile(tmpLocalMarkPath, tmpUpFilePrefix, getCharset());
            //上送银保通服务器
            String[] upFinishRet = sendToBank(tmpReqData, tmpPayDateTime, tmpUpFileName, p_req.reqHeader.transType);
            if (upFinishRet[0].length() == 0) {
                retAts.respCode = "0";
                retAts.reqSeqID = p_req.reqSeqID;
                retAts.respInfo = "文件已生成，并已上送银保通服务器";
                retAts.retCode = "2";
                retAts.retMsg = upFinishRet[1];
            } else {
                retAts.respCode = "-1";
                retAts.reqSeqID = p_req.reqSeqID;
                retAts.respInfo = "文件上传失败，原因:" + upFinishRet[1];
                retAts.retCode = "1";
                retAts.retMsg = upFinishRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代扣授权查询：DBCS
     */
    @Override
    public RetAtsQryAuthForRec d_qry_auth(ReqQryAuthForRec p_req) {
        RetAtsQryAuthForRec retAts = new RetAtsQryAuthForRec(p_req.reqHeader);
        retAts.writeStart();
        try {
            String dateFrom = Format.Date8Format.format(Format.Date10Format.parse(p_req.startDate));
            Date tmpDateNow = new SimpleDateFormat("yyyyMMdd").parse(dateFrom);
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(tmpDateNow);

            String tmpMarkDataDir = getDataFileDirectory(tmpCalendarFrom.getTime()) + File.separator + "auth";
            String tmpLocalMarkPath = StringHelper.trimEnd(tmpMarkDataDir, File.separator) + File.separator + p_req.reqSeqID + ".TXT";
            File localMarkFile = new File(tmpLocalMarkPath);

            if (!localMarkFile.exists()) {
                retAts.respCode = "-1";
                retAts.respInfo = "批次流水映射文件未生成，尚未回盘!";
                retAts.writeAfterDetail();
                return retAts;
            }

            String tmpUpFileName= FileHelper.readFileText(tmpLocalMarkPath, getCharset());

            WriteBankLogLn2("批次映射文件内容:" + tmpUpFileName);
            String tmpDownFileName = "";

            if (StringHelper.hasAnyChar(tmpUpFileName)) {
                tmpDownFileName = "DBCS" + tmpUpFileName.substring(4) + ".TXT";
            } else {
                tmpDownFileName = "DBCS" + tmpUpFileName+".TXT";
            }

            String[] result = fetchResFromBank(tmpDownFileName, tmpDateNow, tmpUpFileName, p_req.reqHeader.transType);
            if ("0".equals(result[0])) {
                retAts.respCode = "0";
                retAts.respInfo = "success";
                StringReader strReader = new StringReader(result[1]);
                BufferedReader tmpReader = new BufferedReader(strReader);
                tmpReader.readLine();
                while (true) {
                    String eachline = tmpReader.readLine();
                    if (eachline == null) {
                        break;
                    }
                    String[] eachNodes = eachline.split("※");
                    RetAtsQryAuthForRecDetail tmpRetDetail = new RetAtsQryAuthForRecDetail();
                    tmpRetDetail.iSeqno = eachNodes[11].trim();
                    tmpRetDetail.authCode = eachNodes[11].trim();
                    tmpRetDetail.oppAct = eachNodes[2].trim();
                    tmpRetDetail.oppActName = eachNodes[3].trim();
                    tmpRetDetail.deadLine = Format.Date8Format.format(tmpDateNow);

                    String tmpRespCode = eachNodes[9].trim();
                    String tmpRespInfo = eachNodes[10].trim();
                    if ("AAAA".equals(tmpRespCode)||("在批量签约表中已存在").equals(tmpRespInfo)||("在客户签约信息表中已存在").equals(tmpRespInfo)) {
                        tmpRetDetail.transState = "2";
                    } else {
                        tmpRetDetail.transState = "3";
                    }
                    tmpRetDetail.payCode = tmpRespCode;
                    tmpRetDetail.payInfo = eachNodes[10].trim();
                    retAts.writeRetDetail(tmpRetDetail);
                }

            } else {
                retAts.respCode = result[0];
                retAts.respInfo = result[1];
                retAts.writeAfterDetail();
                return retAts;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }

        if (retAts.getWriteRdCount() <= 0) {
            retAts.writeRetHead();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsQryRecAuthInfo d_qry_authInfo(ReqQryRecAuthInfo p_req) throws Exception {
        return null;
    }
}
